package com.guiji.quartz.domain;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.task.DataSaveUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 不需要代理
 * @author: wangxw
 * @date 2021/12/16 10:32
 */
public class Gizmodo {
	private static final Logger log = LoggerFactory.getLogger(Gizmodo.class);
	private static final String baseUrl = "https://gizmodo.com/tech/gadgets";
	private static final String domain = "https://gizmodo.com";

	public static void mainMethod() throws Exception {

		HttpResponse response = null;
		try {
			response = HttpRequest.get(baseUrl)
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3194.4 Safari/537.36")
				.setConnectionTimeout(30000)
				.execute();

			if (null != response && response.getStatus() == 200) {
				List<HttpCookie> cookies = response.getCookies();
				String resp = response.body();
				Set<String> resUrl = getUrl(resp);
				getContent(resUrl, cookies);
			} else {
				log.error(baseUrl + String.valueOf(response.getStatus()));
			}

		} catch (Exception e) {
			log.error(String.format("访问 {} 失败", baseUrl) + e);
			return;
		}
	}


	private static void getContent(Set<String> listContent, List<HttpCookie> cookies) throws MalformedURLException, URISyntaxException, InterruptedException {
		for (String url : listContent) {
			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer(domain).append(url).toString();
			}
			if (null != cookies && cookies.size() > 0) {
				CookieManager ccm = new CookieManager();
				CookieStore CookieStore = ccm.getCookieStore();
				for (HttpCookie cookie : cookies) {
					URL domainUrl = new URL(domain);
					CookieStore.add(domainUrl.toURI(), cookie);
				}
				HttpRequest.setCookieManager(ccm);
			}

			log.info("listContent长度-{},getContent执行到-{}", listContent.size(), url);
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url)
					.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
					.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
					.header("Accept-Encoding", "gzip, deflate")
					.header("Refer", baseUrl)
					.setConnectionTimeout(30000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				//"title": "Huawei Made a Smart Water Bottle That Runs HarmonyOS Because Why Not",

				String pattern = "\"title\":\"(.*?)\",\"";
				Pattern p = Pattern.compile(pattern);
				Matcher m = p.matcher(doc);
				while (m.find()) {
					title = m.group(1);
				}

			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			StringBuffer content = new StringBuffer();
			String contentStr = null;
			try {

				//"articleBody": "
				String pattern = "\"articleBody\":\"(.*?)\",\"";
				Pattern p = Pattern.compile(pattern);
				Matcher m = p.matcher(doc);
				while (m.find()) {
					contentStr = m.group(1);
					contentStr = contentStr.replace("\\n", "$$$");
				}
			} catch (Exception e) {
				continue;
			}

			List<String> newImgs = new ArrayList<>();
			String img = null;
			try {
				String pattern = "data-srcset=\"(.*?) ";
				Pattern p = Pattern.compile(pattern);
				Matcher m = p.matcher(doc);
				if (m.find()) {
					img = m.group(1);
					newImgs.add(img);
				}


			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			} finally {
			}

			Date date = new Date();
			if (contentStr.length() > 50000 || contentStr.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				System.out.println("=======================================================");
				System.out.println(url);
				System.out.println(title);

				for (Object imgitem : newImgs) {
					System.out.println(" " + imgitem);
				}
				System.out.println(contentStr);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
				DataSaveUtil.saveData(title, contentStr, newImgs, url, date, baseUrl, "gizmodo-Gadgets");
				log.info(Thread.currentThread().getName() + "-----------------gizmodo-Gadgets ----------------");
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static Set<String> getUrl(String content) {
		Set<String> res = new HashSet<>();
		String pattern = "https://gizmodo.com/[a-z]{5,50}.*?-[0-9]{8,11}";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			String temp = m.group();
			if (temp.contains("-") && !temp.contains("<")) {
				res.add(temp);
			}

		}
		return res;
	}


//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}

}




